package com.thinkgem.jeesite.modules.cms.web.login;

import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.accountinfo.entity.AccountInfo;
import com.thinkgem.jeesite.modules.accountinfo.service.AccountInfoService;
import com.thinkgem.jeesite.modules.config.entity.weixin.ConfigWechat;
import com.thinkgem.jeesite.modules.config.service.weixin.ConfigWechatService;
import com.thinkgem.jeesite.modules.front.entity.cart.GenCart;
import com.thinkgem.jeesite.modules.front.service.cart.GenCartService;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.web.HttpRequestor;

import net.sf.json.JSONObject;

/**
 * 登录Controller
 * @author ws
 * @version 2017-1-5
 */
@Controller
@RequestMapping("${frontPath}")
public class WeixinLoginController extends BaseController{
    private static Log log = LogFactory.getLog(WeixinLoginController.class);
    private String password="123456";
    @Autowired
    GenCartService genCartService;
    
    @Autowired
    SystemService systemService;
    
    @Autowired
    AccountInfoService accountInfoService;
    
    @Autowired
    ConfigWechatService configWechatService;
    
    /**
     * 微信登录
     * @throws Exception 
     */

    @SuppressWarnings({ "static-access", "unchecked" })
    @RequestMapping(value = "weixinLogin", method = RequestMethod.GET)
    public String weixinLogin(HttpServletRequest request, HttpServletResponse response, Model model,HttpSession session,RedirectAttributes redirectAttributes) throws Exception {
        log.debug("+++++++++++++++++++++++++++++++++++++++++++++++++++");
        Cookie[] cookies = request.getCookies();
        System.out.println(cookies);
        String code = request.getParameter("code");
        ConfigWechat configWechat = configWechatService.getConfigWechat();
        AccountInfo user = (AccountInfo) session.getAttribute("user");
        String appid = configWechat.getAppId();
        String secret = configWechat.getAppSecret();
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
        log.debug("code:" + code + ",appid:" + appid + ",secret:" + secret + ",requestUrl:" + requestUrl);
        //第一次请求 获取access_token 和    
        String oppid = new HttpRequestor().doGet(requestUrl);
        JSONObject oppidObj = JSONObject.fromObject(oppid);
        String access_token = (String) oppidObj.get("access_token");
        String openid = (String) oppidObj.get("openid");
        String requestUrl2 = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
        String userInfoStr = new HttpRequestor().doGet(requestUrl2);
        JSONObject wxUserInfo = JSONObject.fromObject(userInfoStr); 
        log.debug("wxUserInfo:" + wxUserInfo.toString());
        
        if(access_token != null && !"".equals(access_token)){
            if(user!=null){
                AccountInfo acQ =new AccountInfo();
                acQ.setWechatNum(openid);
                acQ = accountInfoService.validateUser(acQ);
                if(acQ!=null){
                  
                    addMessage(redirectAttributes, "此微信账号已经绑定，请换其他微信账号！");
                    return "redirect:"+frontPath+"/userfront/myAccount" ;
                }
                addMessage(redirectAttributes, "微信账号绑定成功！");
                user.setWechatNum(openid);;
                
                session.setAttribute("weixinNickname", wxUserInfo.get("nickname"));
                accountInfoService.save(user);
                return "redirect:"+frontPath+"/userfront/myAccount" ;
            }
             user = new AccountInfo();
             String name = checkname((String)wxUserInfo.get("nickname"));
             user.setWechatNum(openid);
             
            if(accountInfoService.validateUser(user) == null) {
                user.setUsername(name);
                user.setUserStatus(1);
        
                user.setPassWord(systemService.entryptPassword(password));
                session.setAttribute("weixinNickname", (String)wxUserInfo.get("nickname"));
                accountInfoService.save(user);   
            }
            user = accountInfoService.validateUser(user);
            if(user.getUserStatus()==null||"".equals(user.getUserStatus())){
                user.setUserStatus(1);
                accountInfoService.save(user); 
            }
            
            if(user.getUserStatus()==0){
                addMessage(redirectAttributes, "账号已禁用！");
                return "redirect:"+frontPath+"/account/login.html";
            }
            
            Object object = CacheUtils.get(user.getId());
            List<GenCart> carts = null;
            if (object != null) {
                carts  = (List<GenCart>) object;
            } else {
                GenCart genCart = new GenCart();
                genCart.setAccountid(Long.parseLong(user.getId()));
                carts = genCartService.findList(genCart);
                CacheUtils.put(user.getId(), carts);
            }
            session.setAttribute("carts", carts);
            session.setAttribute("count", carts.size());
            session.setAttribute("user", user);
            session.setAttribute("weixinNickname", wxUserInfo.get("nickname"));
            return "redirect:"+frontPath+"/front/index" ;
        }
        /*System.out.println("昵称是："+wxUserInfo.get("nickname"));
        System.out.println("性别是："+wxUserInfo.get("sex"));
        System.out.println("所在城市："+wxUserInfo.get("city"));
        System.out.println("所在城市："+wxUserInfo.get("country"));
        System.out.println("所在省份："+wxUserInfo.get("province"));
        System.out.println("语言是："+wxUserInfo.get("language"));
        System.out.println("用户头像："+wxUserInfo.get("headimgurl"));
        System.out.println("关注时间："+wxUserInfo.get("subscribe_time"));*/
        return "redirect:"+frontPath+"/login" ;
    }
    /**
     * 微信登录
     * @throws Exception 
     */
    @RequestMapping(value = "weixinLoginGZ", method = RequestMethod.GET)
    public String weixinLoginGZ(HttpServletRequest request, HttpServletResponse response,RedirectAttributes
            redirectAttributes, Model model,HttpSession session) throws Exception {
        log.debug("+++++++++++++++++++++++++++++++++++++++++++++++++++");
        String code = request.getParameter("code");
        ConfigWechat configWechat = configWechatService.getConfigWechat();
        String appid = configWechat.getAppIdGz();
        String secret = configWechat.getAppSecretGz();
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
        log.debug("code:" + code + ",appid:" + appid + ",secret:" + secret + ",requestUrl:" + requestUrl);
        //第一次请求 获取access_token 和    
        String oppid = new HttpRequestor().doGet(requestUrl);
        JSONObject oppidObj = JSONObject.fromObject(oppid);
        String access_token = (String) oppidObj.get("access_token");
        String openid = (String) oppidObj.get("openid");
        log.debug("openid:" +openid);
        String requestUrl2 = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
        String userInfoStr = new HttpRequestor().doGet(requestUrl2);
        JSONObject wxUserInfo = JSONObject.fromObject(userInfoStr); 
        log.debug("wxUserInfo:" + wxUserInfo.toString());
        if(access_token != null && !"".equals(access_token)){
            AccountInfo info = new AccountInfo();
            String name = checkname((String)wxUserInfo.get("nickname"));
            info.setWechatNum(openid);
            log.debug("GZ:" + wxUserInfo.toString());
            if(accountInfoService.validateUser(info) == null) {
                info.setUsername(name);
                info.setUserStatus(1);
                info.setWechatNum(openid);
                info.setPassWord(systemService.entryptPassword(password));
                session.setAttribute("weixinNickname", (String)wxUserInfo.get("nickname"));
                accountInfoService.save(info);   
            }
            
            info = accountInfoService.validateUser(info);
            if(info.getUserStatus()==0){
                addMessage(redirectAttributes, "账号已禁用！");
                return "redirect:"+frontPath+"/account/login.html";
            }
            Object object = CacheUtils.get(info.getId());
            List<GenCart> carts = null;
            if (object != null) {
                carts  = (List<GenCart>) object;
            } else {
                GenCart genCart = new GenCart();
                genCart.setAccountid(Long.parseLong(info.getId()));
                carts = genCartService.findList(genCart);
                CacheUtils.put(info.getId(), carts);
            }
            session.setAttribute("carts", carts);
            session.setAttribute("count", carts.size());
            session.setAttribute("user", info);
            return "redirect:"+frontPath+"/front/index" ;
        }
    
        /*System.out.println("昵称是："+wxUserInfo.get("nickname"));
        System.out.println("性别是："+wxUserInfo.get("sex"));
        System.out.println("所在城市："+wxUserInfo.get("city"));
        System.out.println("所在城市："+wxUserInfo.get("country"));
        System.out.println("所在省份："+wxUserInfo.get("province"));
        System.out.println("语言是："+wxUserInfo.get("language"));
        System.out.println("用户头像："+wxUserInfo.get("headimgurl"));
        System.out.println("关注时间："+wxUserInfo.get("subscribe_time"));*/
        return "redirect:"+frontPath+"/login" ;
    }
    
    //微信解绑
    @RequestMapping("wxUnbundling")
    public String weixinUnbundling(String id,HttpSession session){
        AccountInfo info = accountInfoService.get(id);
        info.setWechatNum(null);
        accountInfoService.save(info);
        session.setAttribute("weixinNickname",null);
        return "redirect:"+frontPath+"/userfront/myAccount";
    }
    
    /**
     * 微信登录
     * @throws Exception 
     */
    @RequestMapping(value = "weixinForLogin", method = RequestMethod.GET)
    public void forLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ConfigWechat configWechat = configWechatService.getConfigWechat();
        String state = request.getSession().getId();
        response.sendRedirect("https://open.weixin.qq.com/connect/qrconnect?appid=" +configWechat.getAppId()+ "&redirect_uri=https://gainseng.com/jeesite/f/weixinLogin&response_type=code&scope=snsapi_login&state="+state+"");
    }
    
    public String checkname(String name){
        AccountInfo user = new AccountInfo();
        user.setUsername(name);
        List<AccountInfo> list = accountInfoService.findList(user);
        if(list.size()>0){
            name=name+list.size();
        }
        return name;
    }
}